package com.woniuxy.controller;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 曾令忠
 * @Description:
 * @Date: 2020/7/4 0004-上午 9:51
 */
@RestController
public class SecKillController {
    @Autowired
    public RedisTemplate<String,Object> redisTemplate;

    @Resource
    private Redisson redisson;


    @RequestMapping("kill")
    public boolean kill(){
        String lock = "lock";
        RLock rLock = redisson.getLock(lock);
        boolean flag = false;
        try {
            rLock.lock();
            //获取库存
            int num = (Integer)redisTemplate.opsForValue().get("key");
            //判断库存
            if(num>0){
                System.out.println("抢购成功，剩余："+ --num);
                redisTemplate.opsForValue().set("key",num);
                flag = true;

            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }

        return flag;
    }
    @RequestMapping("kill2")
    public boolean kill2(){
        String lock = "lock";
        String id = UUID.randomUUID().toString();
        boolean flag = false;
        try {
//            flag = redisTemplate.opsForValue().setIfAbsent(lock,"woniuxy");
//            redisTemplate.expire(lock,10, TimeUnit.SECONDS);//过期时间
            //保证设加锁和设置过期时间同时成功
            flag = redisTemplate.opsForValue().setIfAbsent(lock,id,10,TimeUnit.SECONDS);
            if (!flag){
                //获取失败，返回不处理
                return flag;
            }

            //获取库存
            int num = (Integer)redisTemplate.opsForValue().get("key");
            //判断库存
            if(num>0){
                System.out.println("抢购成功，剩余："+ --num);
                redisTemplate.opsForValue().set("key",num);

            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            String resultId = (String)redisTemplate.opsForValue().get("key");
            if ((id.equals(resultId))){
                //释放锁
                redisTemplate.delete(lock);
            }
        }

        return flag;
    }

}
